import { ref, SetupContext } from 'vue';
import { ListgroupItem } from '../listgroup/listgroup.type';
import { UPDATE_MODEL_EVENT } from '../../utils/constants';
export default function(ctx: SetupContext){
  const selectedItems = ref<ListgroupItem[]>([]);
  return {
    ref: selectedItems,
    add(item: ListgroupItem){
      const items = selectedItems.value;
      const values = [];
      for(let i=0,len=items.length;i<len;i++){
        if(items[i].value === item.value){
          //已存在
          return i;
        }
        values.push(items[i].value);
      }
      item.selected = true;
      items.push(item);
      values.push(item.value);
      ctx.emit(UPDATE_MODEL_EVENT,values);
      return true;
    },
    remove(item: ListgroupItem){
      const items = selectedItems.value;
      const values = [];
      let removeIndex = -1;
      for(let i=0,len=items.length;i<len;i++){
        if(items[i].value === item.value){
          removeIndex = i;
          items[i].selected = false;
        }else{
          values.push(items[i].value);
        }
      }
      if(removeIndex !== -1){
        items.splice(removeIndex,1);
        ctx.emit(UPDATE_MODEL_EVENT,values);
        return removeIndex;
      }
      return false;
    },
    clear(isEmit?: boolean){
      selectedItems.value.forEach((item) => {
        item.selected = false;
      });
      selectedItems.value = [];
      isEmit && ctx.emit(UPDATE_MODEL_EVENT,[]);
    },
    exist(target: ListgroupItem | string | number){
      let result = false;
      selectedItems.value.forEach((item) => {
        if(typeof target === 'object'){
          if(target === item){
            result = true;
            return false;
          }
        }else if(item.value === target){
          result = true;
          return false;
        }
      });
      return result;
    }
  };
}